#include"tcp_socket.hpp"
#include<functional>

typedef std::function<void(std::string& req,std::string* resp)> Handle;
class TcpServer{
    public:
    TcpServer(std::string ip,u_int16_t port):_ip(ip),_port(port)
    {}
    bool start(Handle handle){
        //1.创建socket
        CHECK_RET(_listen_sock.Socket());
        //2.绑定套接字
        CHECK_RET(_listen_sock.Bind(_port,_ip));
        //3.监听套接字
        CHECK_RET(_listen_sock.Listen());
        //4.进入事件循环
        for(;;){
            //5.接收连接
            TcpSocket _data_sock;
            std::string client_ip;
            u_int16_t client_port=0;
            if(!_listen_sock.Accept(&_data_sock,&client_ip,&client_port)){
                continue;
            }
            printf("child[%s %d] connect!\n",client_ip.c_str(),client_port);
            for(;;){
                //6.进行通信
                std::string req;
                bool ret=_data_sock.Recv(&req);
                if(!ret){
                    printf("[child %s %d] disconnect!\n",client_ip.c_str(),client_port);
                    _data_sock.Close();
                    break;
                }
                std::string resp;
                handle(req,&resp);
                _data_sock.Send(resp);
                printf("child[%s %d] req:%s  resp:%s \n",client_ip.c_str(),client_port,req.c_str(),resp.c_str());
            }
        }
    }
    private:
    TcpSocket _listen_sock;
    std::string _ip;
    u_int16_t _port;
};